<?php
class ZendX_Service_Queryresult
{
	static public function getQueryResult($qb, $param=array(), $filter=array())
	{
    	$select = $qb->getDQLPart('select');
		
    	if (!$qb->getDQLPart('where')) {
    		$qb->where("1=1");
    	}    	
    	
        $flag = 0;
        foreach ($filter as $v)
        {
        	if($v['data']['type'] == 'string')
        	{
        		$qb->andWhere("{$v['field']} like :param{$flag}")
        			->setParameter("param{$flag}", $v['data']['value'].'%'); 
        		$flag += 1;
        	}
        	else if($v['data']['type'] == 'numeric' || $v['data']['type'] == 'date')
        	{
        		$compare = null;
        		if($v['data']['comparison'] == 'lt')
        		{
        			$compare = '<';
        			
        		}
        		else if($v['data']['comparison'] == 'gt')
        		{
        			$compare = '>';
        		}
        		else if($v['data']['comparison'] == 'eq')
        		{
        			$compare = '=';
        		}
        		
        		if (!is_null($compare))
        		{   
        		    $filterParam = $v['data']['value'];
        			if ($v['data']['type'] == 'date')
        			{
        				$format = 'm/d/Y';
						$date = DateTime::createFromFormat($format, $filterParam);
        				$filterParam = $date->format('Y-m-d');
        			}
        			    			
        			$qb->andWhere("{$v['field']} {$compare} :param{$flag}")
        		   		->setParameter("param{$flag}", $filterParam);
        		   	$flag += 1;
        		}        		
        	}
        }
        
        $from = $qb->getDQLPart('from');
        $qb->resetDQLPart('select');
        $qb->add('select', $qb->expr()->count($from[0]->getAlias()));
        $query = $qb->getQuery();
        
        $total = $query->getSingleScalarResult();
        
        $qb->resetDQLPart('select');          
        $qb->add('select', $select);
        if (array_key_exists('limit', $param)) {
        	$qb->setFirstResult($param["start"])
            	->setMaxResults($param["limit"]);
        }            
            
        $query = $qb->getQuery();
        $items = $query->getArrayResult();
        
        return array('totalCount' => $total, 'source' => $items);
	}
}
?>